#encoding:utf-8
import numpy as np
from decimal import Decimal

from pojo.entity.BaseEntity import BaseEntity
from pojo.entity.bizExcept import  ErrMsgExcept

class Quotation(BaseEntity):

    realTransactionId=None

    symbol=None
    market=None

    lastClosePrice=None
    open=None
    close=None
    high=None
    low=None

    limitUpFlag=None
    limitDnFlag=None
    suspensionFlag=None

    amount=None
    volume=None

    bidPrice1=None
    bidPrice2=None
    bidPrice3=None
    bidPrice4=None
    bidPrice5=None

    bidVol1=None
    bidVol2=None
    bidVol3=None
    bidVol4=None
    bidVol5=None

    aidPrice1=None
    aidPrice2=None
    aidPrice3=None
    aidPrice4=None
    aidPrice5=None

    aidVol1=None
    aidVol2=None
    aidVol3=None
    aidVol4=None
    aidVol5=None

    entryTime=None

    def isLimitUp(self):
        notNullFlag=self.open is not None and self.open!=0.0
        equalFlag=self.open==self.high and self.open==self.low and self.open==self.close
        limitUpFlag=self.open>self.lastClosePrice
        return notNullFlag and  equalFlag and limitUpFlag

    def isLimitDn(self):
        notNullFlag = self.open is not None and self.open != 0.0
        equalFlag = self.open == self.high and self.open == self.low and self.open == self.close
        limitDnFlag = self.open < self.lastClosePrice
        return notNullFlag and equalFlag and limitDnFlag

    def isSuspension(self):
        notNullFlag = self.open is not None and self.open == 0.0
        equalFlag = self.open == self.high and self.open == self.low and self.open == self.close
        return notNullFlag and equalFlag

    def getCurrentPrice(self):
        return self.lastClosePrice if self.suspensionFlag else self.close

    def getBuyPrice(self,times=0):
        """买时，参照卖价。"""
        buyPrices=[self.aidPrice1,self.aidPrice2,self.aidPrice3,self.aidPrice4,self.aidPrice5]
        return self._getOprPrice(buyPrices,times)

    def getSellPrice(self,times=0):
        """卖时，参照买价"""
        sellPrices=[self.bidPrice1,self.bidPrice2,self.bidPrice3,self.bidPrice4,self.bidPrice5]
        return self._getOprPrice(sellPrices,times)

    def _getOprPrice(self,prices,times):
        validPrices = [price for price in prices if price is not None and price > 0]
        if self.isSuspension():
            return self.lastClosePrice
        if len(validPrices)==0 :
            extraPrice=self.lastClosePrice if self.suspensionFlag else self.close
            if extraPrice is None or extraPrice ==0 :
                raise ErrMsgExcept("异常行情：{quotation}".format(quotation=self))
            else:
                return extraPrice

        index = np.clip(times, 0, len(prices) - 1)
        return validPrices[index]


    def getLimitPrice(self,last_close_price, multi):
        "计算 一字板涨跌停价格。"
        limit_price = Decimal(last_close_price) * Decimal(100) * Decimal(multi)
        return float('%.2f' % (limit_price / 100))

    def changeFormat(self):
        notChangedKeys=["symbol","market","entryTime"]
        for key,val in self.__dict__.items():
            if key in notChangedKeys:
                continue
            self.__dict__[key]=float(val.decode("utf-8"))

        return self

    def getTableName(self):
        pass

    def getTableFieldMap(self):
        pass

    def __str__(self):
        descDict = self.__dict__
        return """Quotation-----{desc}""".format(
            desc=",".join(
                ["{key}:{val}".format(key=key, val=val.encode("utf-8") if isinstance(val, unicode) else val) for
                 key, val in descDict.items()])
        )
